Dictionaries¶

🎨 {}¶

In [1]:
meals = {
    'breakfast': 'oatmeal',
    'lunch': 'leftovers',
    'dinner': 'spaghetti'
}

NOTES

  • curly braces, colons, commas
  • key-value pairs
  • this is a dictionary or dict
In [2]:
type(meals)
Out[2]:
dict
In [3]:
meals
Out[3]:
{'breakfast': 'oatmeal', 'lunch': 'leftovers', 'dinner': 'spaghetti'}
In [5]:
meals['breakfast']
Out[5]:
'oatmeal'

NOTES

  • What is this going to print?
  • square brackets for item lookup
  • you provide the key and you get the associated value back
In [6]:
meals['lunch']
Out[6]:
'leftovers'
In [7]:
meals['leftovers']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 meals['leftovers']

KeyError: 'leftovers'

NOTES

  • You can only lookup by keys, not by values
  • When you try to lookup a key that is not in the dictionary, you get a KeyError
In [8]:
meals = {
    'breakfast': 'candy',
    'lunch': 'pizza',
    'breakfast': 'oatmeal',
    'dinner': 'sandwiches'
}
In [9]:
meals
Out[9]:
{'breakfast': 'oatmeal', 'lunch': 'pizza', 'dinner': 'sandwiches'}

NOTES

  • You can't have duplicate keys
  • If you assign to the same key again, the new value overwrites the old value
In [10]:
for meal, offering in meals.items():
    print(f'For {meal} you get {offering}. 😋') 
For breakfast you get oatmeal. 😋
For lunch you get pizza. 😋
For dinner you get sandwiches. 😋
In [11]:
for meal in meals: # iterate over keys
    print(meal)
breakfast
lunch
dinner
In [12]:
for dish in meals.values():  # iterate over values
    print(dish)
oatmeal
pizza
sandwiches

NOTES

  • meals.items() returns a sequence of key-value pairs, which we unpack into meal and offering
In [13]:
list(meals.items())
Out[13]:
[('breakfast', 'oatmeal'), ('lunch', 'pizza'), ('dinner', 'sandwiches')]

🖌 in + dict¶

In [14]:
hometowns = {
    'Dallin Oaks': 'Provo, UT',
    'Jeffery Holland': 'St George, UT',
    'Merril Bateman': 'Lehi, UT',
    'Cecil Samuelson': 'Salt Lake City, UT',
    'Kevin Worthen': 'Dragerton, UT',
    'Shane Reese': 'Logan, UT'
}

NOTES

  • we can use numbers as keys too, not just strings
In [15]:
'Shane Reese' in hometowns
Out[15]:
True
In [16]:
'Karl Maeser' in hometowns
Out[16]:
False
In [19]:
for person in ['Kevin Worthen', 'Henry Eyring', 'Shane Reese', 'Ernest Wilkinson', 'Karl Maeser']:
    if person in hometowns:
        print(f'{person} was born in {hometowns[person]}.')
    else:
        print(f"I don't know where {person} was born.")
Kevin Worthen was born in Dragerton, UT.
I don't know where Henry Eyring was born.
Shane Reese was born in Logan, UT.
I don't know where Ernest Wilkinson was born.
I don't know where Karl Maeser was born.

NOTES

  • We saw earlier that asking for a key-value that doesn't exist in a dictionary gives us a KeyError
  • Use key in dict syntax to check that the key is present
    • and if it isn't, do something else

🧑🏽‍🎨 The world needs more emojis¶

You are given a dictionary mapping words to emojis.

Replace all instances of a word with it's corresponding emoji. Ignore case.

So, given a dictionary

emojis = {'dog': '🐶', 'cat': '🐱', 'tree': '🌳', 'bird': '🐦'}

The phrase

My dog has fleas.

Becomes

My 🐶 has fleas.
In [ ]:
! python for_class/emojis_solution.py "The Dogs chased the cat which chased the bird that sat in the tree in my yard."

🧑🏻‍🎨 Team Assignments¶

Community members want to register for the Rec Center sports teams.

You have a dictionary that maps age groups to team names.

Map a list of tuples containing a name and age to a list of tuples containing name and team.

To compute a participants age group, find the nearest multiple of 3 that is less than or equal to the participant age.

If the participant does not have an age-group assignment, they go in team "Old Fogies".

👨🏾‍🎨 Cipher¶

Given a dictionary mapping letters to other letters (called a "codex"), encode a message.

The codex only contains lower-case letters, but you should encode upper-case letters also. Preserve casing.

Key Ideas¶

  • dict {}
  • Iterating over the key-value pairs in a dictionary
  • key in dict
  • Lookup information using []